package com.example.demo2.manager;

import com.example.demo2.bean.Cd;
import com.example.demo2.bean.CdPlayer;
import com.example.demo2.bean.Library;
import com.example.demo2.bean.Track;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * CD服务器管理器，负责控制CD播放器的各种操作
 *
 */
@Component
public class CDServerManager {
    @Autowired
    private CdPlayer cdPlayer;

    @Autowired
    private Library library;

    /**
     * 打印CD当前状态
     */
    public void printsCDState() {
        System.out.println(cdPlayer.getLcdStatus());
    }

    /**
     * 列出CD库中的所有CD及曲目
     */
    public void listCDLibrary(){
        SimpleDateFormat format = new SimpleDateFormat("mm:ss");
        StringBuilder buf = new StringBuilder();
        int cdIndex = 0;
        for (Cd cd : library.getCollection()) {
            buf.append(cdIndex++).append(": ").append(cd.getName()).append("\n");
            int trackIndex = 0;
            for (Track track : cd.getTracks()) {
                buf.append("  ").append(trackIndex++).append(": ")
                        .append(track.getName()).append("  ")
                        .append(format.format(new Date(track.getLength()*1000)))
                        .append("\n");
            }
        }
        System.out.println(buf.toString());
    }

    /**
     * 将指定索引的CD加载到播放器
     * @param index CD在库中的索引
     */
    public void loadCdToPlayer(int index){
        try {
            if (index < 0 || index >= library.getCollection().size()) {
                System.out.println("Cd with index " + index + " not found, check library");
                return;
            }
            Cd cd = library.getCollection().get(index);
            cdPlayer.load(cd);
        } catch (Exception e) {
            System.out.println("Error loading cd with index " + index + ": " + e.getMessage());
        }
    }

    /**
     * 播放CD
     */
    public void playCd(){
        cdPlayer.play();
    }

    /**
     * 停止播放CD
     */
    public void stopCd(){
        cdPlayer.stop();
    }

    /**
     * 暂停播放CD
     */
    public void pauseCd(){
        cdPlayer.pause();
    }

    /**
     * 弹出CD
     */
    public void ejectCd(){
        cdPlayer.eject();
    }

    /**
     * 快进CD
     */
    public void forwardCd(){
        cdPlayer.forward();
    }

    /**
     * 快退CD
     */
    public void backCd(){
        cdPlayer.back();
    }
}
